package com.lv.suyiyong.hfr.fragment

import android.Manifest
import android.graphics.Color
import android.os.Bundle
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.lv.common.adapter.ContainerPagerAdapter
import com.lv.common.base.BaseFragment
import com.lv.common.bean.CommonSelectedBean
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.ktx.setViewFlipper
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.PermissionXUtils
import com.lv.common.utils.PermissionXUtilsCallback
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.showToast
import com.lv.service.model.EditorViewModel
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.databinding.FragmentHomeBinding


/**
 * 作者： ygx
 * 创建日期：2023/2/10 11:24 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：应用商城需要的权限：ABCDEFGHIJKLMNO
 */
class HomeFragment : BaseFragment(), View.OnClickListener {
    private val mTabs = mutableListOf<CommonSelectedBean>()
    private val mFragment = mutableListOf<Fragment>()
    private var mAdapter: ContainerPagerAdapter? = null
    private val mEditorViewModel: EditorViewModel by activityViewModels()
    private var mBinding: FragmentHomeBinding? = null
    override fun getLayoutRes() = R.layout.fragment_home
    override fun bindView(view: View, savedInstanceState: Bundle?): ViewDataBinding {
        mBinding = FragmentHomeBinding.bind(view).apply {
            StatusBarUtil.setHeightAndPadding(requireContext(), viewSub)
            initSingleClickListener(viewSearch, vSearch)
        }

        return mBinding!!
    }

    override fun initConfig() {
        super.initConfig()
        initTabAdapter()
        /*// 获取定位信息后的回调，
        locationUtil.locationCallBack = {
            val address = locationUtil.getAddress(requireContext(), it)
            try {
                val city = "${address?.locality}"
//                val town = address?.getAddressLine(0)
                var featureName = address?.featureName
                if (featureName.isNullOrEmpty()) {
                    featureName = address?.thoroughfare + address?.subThoroughfare
                }
                SPStaticUtils.put(Constants.ADDRESS_CITY_RECEIPT_KEY, city)
                SPStaticUtils.put(Constants.ADDRESS_TOWN_RECEIPT_KEY, featureName)
            } catch (e: Exception) {
            }
        }*/
//        UserDbHelper.getLiveUserInfo(requireContext()).observeKt { userInfo ->
//            if (userInfo != null && userInfo.id.isNotEmpty()) {
//                mUserInfo = userInfo
//
//            }
//        }


    }

    private fun initTabAdapter() {
        mFragment.clear()
        mFragment.add(HomeFactoryFragment.newInstance())
        mFragment.add(HomeGoodsFragment.newInstance())
        mTabs.clear()
        mTabs.add(CommonSelectedBean("找厂家"))
        mTabs.add(CommonSelectedBean("找商品"))
        mAdapter = ContainerPagerAdapter(
            childFragmentManager, lifecycle, mTabs
        )
        mAdapter?.listener = object : ContainerPagerAdapter.CirTabListener {
            override fun getFragment(position: Int): Fragment {
                val fragment: Fragment = mFragment[position]
                return fragment
            }
        }
        mBinding?.viewPager?.adapter = mAdapter
        TabLayoutMediator(mBinding?.tabLayout!!, mBinding?.viewPager!!) { tabLayout, position ->
            // 设置Tab的标题
            val customView =
                tabLayout.setCustomView(R.layout.home_top_tab)
            val tvTabTitle = customView.customView?.findViewById<TextView>(R.id.tv_name)
            tvTabTitle?.text = mTabs[position].name
        }.attach()
//
        mBinding?.viewPager?.offscreenPageLimit = mTabs.size
        mBinding?.tabLayout?.addOnTabSelectedListener(object :
            TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                val position = tab?.position
                mTab = position ?: 0
//                switchFragment(mFragment[mTab])
                val textView = tab?.customView?.findViewById<TextView>(R.id.tv_name)
                val mViewLine = tab?.customView?.findViewById<View>(R.id.view_line)
                mViewLine?.visibility = View.VISIBLE
                textView?.paint?.isFakeBoldText = true
                textView?.setTextSize(TypedValue.COMPLEX_UNIT_SP, 19f)

            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                val textView = tab?.customView?.findViewById<TextView>(R.id.tv_name)
                textView?.paint?.isFakeBoldText = false
                textView?.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
                val mViewLine = tab?.customView?.findViewById<View>(R.id.view_line)
                mViewLine?.visibility = View.GONE

            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }
        })
//        switchFragment(mFragment[mTab])
        setSelectedTab(mTab)
    }

    private var mTab = 0
    private fun setSelectedTab(position: Int) {
//        mBinding?.tabLayout?.selectTab(mBinding?.tabLayout?.getTabAt(position))
        mBinding?.viewPager?.currentItem = position
        val tabAt = mBinding?.tabLayout?.getTabAt(position)
        val titleTab = tabAt?.customView?.findViewById<TextView>(R.id.tv_name)
        titleTab?.paint?.isFakeBoldText = true
        titleTab?.setTextSize(TypedValue.COMPLEX_UNIT_SP, 19f)
        val mViewLine = tabAt?.customView?.findViewById<View>(R.id.view_line)
        mViewLine?.visibility = View.VISIBLE

    }

//    private var currentFragment: Fragment? = null
//    private fun switchFragment(fragment: Fragment) {
//        if (currentFragment == fragment) {
//            return
//        }
//        childFragmentManager.fragments.forEach {
//            if (it.isAdded && !it.isHidden) {
//                childFragmentManager.beginTransaction().hide(it).commit()
//            }
//        }
//        if (!fragment.isAdded) {
//            childFragmentManager.beginTransaction().add(R.id.view_pager, fragment).commit()
//        } else {
//            childFragmentManager.beginTransaction().show(fragment).commit()
//        }
//        currentFragment = fragment
//
//    }

    override fun initData() {
        super.initData()
        mEditorViewModel.liveSearchData.observe(this) {
            setSearchData(it)
        }
    }

    fun setSearchData(titles: List<String>) {
        mBinding?.marqueeBanner?.setViewFlipper(requireContext(), titles, 3000) { i ->
            val mLayout: View =
                LayoutInflater.from(requireContext())
                    .inflate(R.layout.item_text_flipper, null)
            val tvTitle = mLayout.findViewById<TextView>(R.id.tv_content)
            //赋值
            tvTitle.text = titles[i]
//            marqueeBanner.setSafeListener {
//                ARouter.getInstance().build(ARoutUtils.HomeSearchActivity)
//                    .withString("searchCode", "0").navigation()
//            }
//            if (mNewYear == 1) {
//                tvTitle.setTextColor(Color.parseColor("#FFE5AE"))
//            }
            return@setViewFlipper mLayout
        }
    }

    override fun initEvents() {
        super.initEvents()

//        rigestEventBus()
    }

    private fun checkPermissionLoction() {
        val permissions = mutableListOf(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_BACKGROUND_LOCATION,
        )
        // 用于在您浏览、搜索或参与特定活动时，向您展示当前城市服务信息，以提升体验。不申请该权限不影响APP的正常使用。是否同意去申请该权限？
        PermissionXUtils.checkPermissBefore(
            this,
            permissions,
            "上传回执需要授予位置权限，用于展示当前城市的服务信息，以提升体验。不申请该权限不影响APP的正常使用。",
            object : PermissionXUtilsCallback {
                override fun permissionCallback(
                    allGranted: Boolean,
                    grantedList: List<String?>,
                    deniedList: List<String?>,
                ) {
                    if (allGranted) {
//                        locationUtil.initLocationManager()
//                        LocationUtils.getInstance().getLocations(requireContext())

                    }

                }

                override fun fotPermsission() {

                }


            },
        )
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.view_search -> {
                ARouter.getInstance().build(ARoutUtils.HomeSearchActivity).navigation()
            }

            R.id.v_search -> {
                val text =
                    (mBinding?.marqueeBanner?.currentView?.findViewById<TextView>(R.id.tv_content)?.text
                        ?: "").toString()
                ARouter.getInstance().build(ARoutUtils.HomeSearchResultActivity)
                    .withString("search", text).navigation()
            }

        }
    }

//    private fun rigestEventBus() {
//        LiveEventBus.get(
//            HomeRefreshEvent::class.java,
//        ).observe(
//            this
//        ) { s ->
//            if (s != null) {
//                val message = s.message
//                val offlineMessageBean = s.offlineMessage
//                val pushMessage = s.pushMessage
//                if (message != null) {
//                    val conversationID = message.conversationID
//                    val unreadCount = message.unreadCount
//                    mTvMsgTotalUnread?.text = "$unreadCount"
//                    mTvMsgTotalUnread?.visibility = if (unreadCount > 0) View.VISIBLE else View.GONE
//                    if (conversationID.contains("syy0000")) {
//                        if (conversationID == Constants.ID_TZ) {
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        } else if (conversationID == Constants.ID_FW) {
//                            ARouter.getInstance().build(ARoutUtils.MessageVisitRecodeActivity)
//                                .navigation()
//                        } else if (conversationID == Constants.ID_HD) {
//                            ARouter.getInstance().build(ARoutUtils.MessageInteractionActivity)
//                                .navigation()
//                        }
//
//                    } else {
//                        mTvMessageText?.text = "新增聊天消息"
//                        mViewChatBg?.setOnClickListener {
//                            //点击后，页面切换到消息Tab
//                            val showName = message.showName
//                            TUIUtils.startChat(
//                                conversationID,
//                                showName,
//                                V2TIMConversation.V2TIM_C2C
//                            )
//                        }
//                    }
//                    mIvMore?.visibility = View.VISIBLE
//                }
//                if (offlineMessageBean != null) {
//                    if (offlineMessageBean.action == OfflineMessageBean.REDIRECT_ACTION_CHAT) {
//                        if (TextUtils.isEmpty(offlineMessageBean.sender)) {
//                            return@observe
//                        }
//                        TUIUtils.startChat(
//                            offlineMessageBean.sender,
//                            offlineMessageBean.nickname,
//                            offlineMessageBean.chatType
//                        )
//                    }
//                }
//                if (pushMessage != null) {
//                    when (pushMessage.t) {
//                        "100" -> {//完善信息
//                            mTvMessageText?.text = "重要通知"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//                        "102" -> {//书刊上新
//                            mTvMessageText?.text = "书刊上新"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//                        "103" -> {// 商品风险下架
//                            mTvMessageText?.text = "商品风险下架"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//                        "104" -> {// 货圈风险下架
//                            mTvMessageText?.text = "货圈风险下架"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//
//                        }
//                        "105" -> {// 货圈审核通过
//                            mTvMessageText?.text = "审核通过"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//                        "106" -> {// 106 货圈审核未通过
//                            mTvMessageText?.text = "审核未通过"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//
//                        "107" -> {// 商品上架通过
//                            mTvMessageText?.text = "审核通过"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//                        "108" -> {// 商品上架拒绝
//                            mTvMessageText?.text = "审核未通过"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//                        "110" -> {// 访问消息
//                            ARouter.getInstance().build(ARoutUtils.MessageVisitRecodeActivity)
//                                .navigation()
//                        }
//                        "111", "112", "113", "114" -> {// 111 点赞货圈 112 关注店铺 113  收藏商品 114  拨打电话
//                            ARouter.getInstance().build(ARoutUtils.MessageInteractionActivity)
//                                .navigation()
//                        }
//                        else -> {
//
//                        }
//                    }
//                }
//
//            }
//        }
//    }
//    override fun isHaveHeadMargin(): Boolean {
//        return false
//    }


    override fun onResume() {
        super.onResume()
        LogUtils.e("onResume")
//        initStatusBar(requireActivity(), true, false)
    }

//    override fun onHiddenChanged(hidden: Boolean) {
//        super.onHiddenChanged(hidden)
//        LogUtils.e("onHiddenChanged==$hidden")
//        if (!hidden) {
//            initStatusBar(requireActivity(), true, false)
//        }
//    }


    override fun onDestroy() {
        super.onDestroy()
    }


//    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
//        if (data != null) {
//            //QQ回调
//            ShareUtils.get().onQqActivityResult(requestCode, resultCode, data)
//        }
//    }

    companion object {
        @JvmStatic
        fun newInstance() = HomeFragment()
    }
}